package controller.v2;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.paypal.api.payments.Payment;
import com.paypal.api.payments.PaymentExecution;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;

import dao.v2.MemberCartVOMapper;
import model.AddressVO;
import model.CashRechargeVO;
import model.LogBuyCashVO;
import model.LogEarnVO;
import model.LogOrder;
import model.MemberLevelItemVO;
import model.MemberVO;
import model.OrderPayVO;
import model.OrderVO;
import model.PackageVO;
import service.v2.AddressService;
import service.v2.ConfigService;
import service.v2.DicService;
import service.v2.GoodTempService;
import service.v2.MemberCartServise;
import service.v2.MemberItemService;
import service.v2.MemberLevelItemService;
import service.v2.MemberService;
import service.v2.MessageService;
import service.v2.MoneyService;
import service.v2.OrderService;
import service.v2.PayService;
import service.v2.PushInterService;
import service.v2.PushService;
import service.v2.SplitService;
import service.v2.UorderPayService;
import service.v2.WechatLoginService;
import util.ConfigUtil;
import util.NumberUtil;
import util.PackageUtil;
import util.PaypalPayment;
import util.PropertieUtil;
import util.PushUtil;
import util.StringUtil;
import util.XMLUtil;

@RequestMapping("/v2/pay")
@Controller
public class PayController {
	
	@Autowired
	private DicService dicService;
	@Autowired
	private MoneyService moneyService;
	@Autowired
	private PayService payService;
	@Autowired
	private MemberLevelItemService memberLevelItemService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private SplitService splitService;
	@Autowired
	private MemberCartVOMapper memberCartVOMapper;
	@Autowired
	private GoodTempService goodTempService;
	@Autowired
	private MemberCartServise memberCartServise;
	@Autowired
	private MemberItemService memberItemService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private PushService pushService;
	@Autowired
	private PushInterService pushInterService;
	
	@Autowired
	private UorderPayService uorderPayService;
	
	@Autowired
	private AddressService addressService;
	/**
	 * 支付状态查询接口
	 */
	@ResponseBody
	@RequestMapping(value="/queryPayOrder",method=RequestMethod.GET)
	public Object queryPayOrder(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			, String no){
		if(no ==null || "".equals(no)){
			PackageUtil.packageParams(10001, "缺少必选参数", "", "");
		}
		OrderPayVO payVO = payService.getPayOrderByNo(no);
		return PackageUtil.packageParams(200,"successs",payVO,"");
	}
	
	@RequestMapping(value = "/paypalReturnUrlNotify")
	public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId, @RequestParam("returnUrl") String returnUrl) {
		try {
			Payment payment = new Payment();
			payment.setId(paymentId);
			PaymentExecution paymentExecute = new PaymentExecution();
			paymentExecute.setPayerId(payerId);
			payment = payment.execute(new APIContext(ConfigUtil.CLIENT_ID, ConfigUtil.CLIENT_SECRET, ConfigUtil.MODE), paymentExecute);
			if (payment.getState().equals("approved")) {
				return "redirect:" + returnUrl;
			}
			return null;
		} catch (PayPalRESTException e) {
			System.out.println(e.getMessage());
		}
		return null;
	}
	
	/**
	 * 兑换券充值 paypal
	 * @param token
	 * @param member_id
	 * @param ticket 兑换券数量
	 * @param rate 折扣
	 * @param type 1充值 2升级
	 * @throws Exception 
	 */
	@RequestMapping(value="/rechargeTicketPayPal",method=RequestMethod.POST)
	public String rechargeTicketPayPal(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String ticket ,String rate, String pay_pwd, String type, String return_url, String cancel_url) throws NumberFormatException, Exception{
		
		//验证参数
		if (ticket == null || rate == null || type==null || lang==null) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
			out.flush();
			out.close();
			return null;
		}
		if (!"en".equals(lang.toLowerCase()) || !StringUtil.isNumeric(ticket) || !StringUtil.isRate(rate) ||  Integer.parseInt(ticket) > Integer.parseInt(configService.loadConfig("TICKET_BUY_MAXNUM")) ||( !"1".equals(type) && !"2".equals(type))||  Integer.parseInt(ticket) < 0) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		memberVO = memberService.getAllInfoById(member_id);
		//体验会员
		if("1".equals(memberVO.getExp_state())){
			memberVO.setLevel(PropertieUtil.loadPropertie("common_level"));
		}
		// 验证可享受充值优惠 验证充值数量大于折扣对应的起批量 1.充值 2升级
		boolean flag = false;
		if("1".equals(type)){
			List<MemberLevelItemVO> enjoy_privilege = memberLevelItemService.selectenjoyPrivilege(memberVO.getLevel());
			for (MemberLevelItemVO memberLevelItemVO : enjoy_privilege) {
				if (rate.equals(memberLevelItemVO.getRate())
						&& Integer.parseInt(memberLevelItemVO.getStart_ticket()) <= Integer.parseInt(ticket)) {
					flag = true;
					break;
				}
			}
		}else if("2".equals(type)){
			List<MemberLevelItemVO> advance_privilege = memberLevelItemService.selectadvancePrivilege(memberVO.getLevel(),member_id);
			for (MemberLevelItemVO memberLevelItemVO : advance_privilege) {
				if (rate.equals(memberLevelItemVO.getRate()) && ticket.equals(NumberUtil.formatDouble(Double.parseDouble(memberLevelItemVO.getNeed_price()) / Double.parseDouble(memberLevelItemVO.getRate()), 0))&& !PropertieUtil.loadPropertie("master_level").equals(memberLevelItemVO.getLevel())) {
					flag = true;
					break;
				}
			}
		}
		if (!flag) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		String price = "0";
		if("1".equals(type)){
			price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
		}else if("2".equals(type)){
			if(Integer.parseInt(ticket) * Double.parseDouble(rate) > 1){
				price = (int)(Double.parseDouble(Integer.parseInt(ticket) * Double.parseDouble(rate) + ""))+"";
			}else{
				price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
			}
		}
		
		String ticket_name = configService.loadConfig("TICKET_NAME");
		System.out.println("实际金额----------------------"+ price);
		price = "2.00";
		// 生成支付单 返回单号
		String no = payService.genPayOrder(3, price, ticket_name+"充值", 5, member_id);
		// 保存参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("ticket", ticket);
		map.put("rate", rate);
		map.put("lang", lang);
		payService.updatePayOrderParams(no, JSON.toJSONString(map));
		
		// 充值
		request.setAttribute("cancel_url", cancel_url);
		request.setAttribute("return_url", return_url);
		request.setAttribute("payType", 2);
		request.setAttribute("order_no", no);
		request.setAttribute("price", price);
		request.setAttribute("body", "order pay");
		return "forward:paypalPrePay";
	}
	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/ticketPaypalNotify",method=RequestMethod.POST)
	public void ticketPaypalNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in ticketPaypalNotify--------------------------------------------");
		payVO =  payService.getPayOrderByNo(request.getParameter("order_id"));
		System.out.println(request.getParameter("order_id"));
		// 判断签名是否正确  
		boolean flag = payService.checkPayPalParam(request);
		if(payVO!=null && flag && "N".equals(payVO.getPay_yn())){
			int re = payService.updateOrderPayFinish(payVO);
			if(re==0){
				return;
			}
			//******************************支付成功业务逻辑start**************************************//
			//关联操作
			JSONObject obj = JSON.parseObject(payVO.getParams());
			//提货券充值 生成日志 修改支付状态
			String conn_no = payService.insertMemberTicket(payVO, payVO.getMember_id(), obj.getString("ticket"), obj.getString("rate"), 2, PropertieUtil.loadPropertie("partner_level"),"0");
			//分润
			memberVO = memberService.getAllInfoById(payVO.getMember_id());
			splitService.split(payVO.getMember_id(), memberVO.getLevel(), 1, obj.getString("ticket"), obj.getString("rate"), conn_no, 0+"", 2+"", "0");
			//充劵时分润推送
			pushInterService.rechargeTicket(conn_no,member_id,"0");
			
			//******************************支付成功业务逻辑end**************************************//
		}else{
			
		}
	}
	
	/**
	 * 兑换券充值 payssion
	* @param token
	 * @param member_id
	 * @param ticket 兑换券数量
	 * @param rate 折扣
	 * @param type 1充值 2升级
	 * @throws Exception 
	 */
	@RequestMapping(value="/rechargeTicketPayssionPay",method=RequestMethod.POST)
	public String rechargeTicketPayssionPay(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String ticket ,String rate, String pay_pwd, String type, String pay_key) throws NumberFormatException, Exception{
		
		//验证参数
		if (ticket == null || rate == null || type==null || lang==null || pay_key==null) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
			out.flush();
			out.close();
			return null;
		}
		List<String> keyList = dicService.getChildNamesByParent(PropertieUtil.loadPropertie("payssion_key"));
		if (!keyList.contains(pay_key) || !"en".equals(lang.toLowerCase()) || !StringUtil.isNumeric(ticket) || !StringUtil.isRate(rate) ||  Integer.parseInt(ticket) > Integer.parseInt(configService.loadConfig("TICKET_BUY_MAXNUM")) ||( !"1".equals(type) && !"2".equals(type))||  Integer.parseInt(ticket) < 0) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		memberVO = memberService.getAllInfoById(member_id);
		//体验会员
		if("1".equals(memberVO.getExp_state())){
			memberVO.setLevel(PropertieUtil.loadPropertie("common_level"));
		}
		// 验证可享受充值优惠 验证充值数量大于折扣对应的起批量 1.充值 2升级
		boolean flag = false;
		if("1".equals(type)){
			List<MemberLevelItemVO> enjoy_privilege = memberLevelItemService.selectenjoyPrivilege(memberVO.getLevel());
			for (MemberLevelItemVO memberLevelItemVO : enjoy_privilege) {
				if (rate.equals(memberLevelItemVO.getRate())
						&& Integer.parseInt(memberLevelItemVO.getStart_ticket()) <= Integer.parseInt(ticket)) {
					flag = true;
					break;
				}
			}
		}else if("2".equals(type)){
			List<MemberLevelItemVO> advance_privilege = memberLevelItemService.selectadvancePrivilege(memberVO.getLevel(),member_id);
			for (MemberLevelItemVO memberLevelItemVO : advance_privilege) {
				if (rate.equals(memberLevelItemVO.getRate()) && ticket.equals(NumberUtil.formatDouble(Double.parseDouble(memberLevelItemVO.getNeed_price()) / Double.parseDouble(memberLevelItemVO.getRate()), 0))&& !PropertieUtil.loadPropertie("master_level").equals(memberLevelItemVO.getLevel())) {
					flag = true;
					break;
				}
			}
		}
		if (!flag) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		String price = "0";
		if("1".equals(type)){
			price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
		}else if("2".equals(type)){
			if(Integer.parseInt(ticket) * Double.parseDouble(rate) > 1){
				price = (int)(Double.parseDouble(Integer.parseInt(ticket) * Double.parseDouble(rate) + ""))+"";
			}else{
				price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
			}
		}
		
		String ticket_name = configService.loadConfig("TICKET_NAME");
		System.out.println("实际金额----------------------"+ price);
//		price = "2.00";
		// 生成支付单 返回单号
		String no = payService.genPayOrder(3, price, ticket_name+"充值", 3, member_id);
		// 保存参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("ticket", ticket);
		map.put("rate", rate);
		map.put("lang", lang);
		map.put("payKey", pay_key);
		payService.updatePayOrderParams(no, JSON.toJSONString(map));
		
		// 充值
		request.setAttribute("payType", 2);
		request.setAttribute("order_no", no);
		request.setAttribute("price", price);
		request.setAttribute("body", "order pay");
		request.setAttribute("payKey", pay_key);
		return "forward:payssionPrePay";
	}
	
	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/ticketPayssionPayNotify",method=RequestMethod.POST)
	public void ticketPayssionPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in ticketPayssionPayNotify--------------------------------------------");
		//解析参数
		Map<String,String> params = payService.resolveAPayssionParam(request);
		payVO =  payService.getPayOrderByNo(params.get("order_id"));
		// 判断签名是否正确  
		boolean flag = payService.checkPayssionParam(payVO, params);
		if(flag && "N".equals(payVO.getPay_yn())){
			int re = payService.updateOrderPayFinish(payVO);
			if(re==0){
				return;
			}
			//******************************支付成功业务逻辑start**************************************//
			//关联操作
			JSONObject obj = JSON.parseObject(payVO.getParams());
			//提货券充值 生成日志 修改支付状态
			String conn_no = payService.insertMemberTicket(payVO, payVO.getMember_id(), obj.getString("ticket"), obj.getString("rate"), 2, PropertieUtil.loadPropertie("partner_level"),"0");
			//分润
			memberVO = memberService.getAllInfoById(payVO.getMember_id());
			splitService.split(payVO.getMember_id(), memberVO.getLevel(), 1, obj.getString("ticket"), obj.getString("rate"), conn_no, 0+"", 2+"", "0");
			//充劵时分润推送
			pushInterService.rechargeTicket(conn_no,member_id,"0");
			
			//******************************支付成功业务逻辑end**************************************//
		}else{
			
		}
	}
	
	/**
	 * 兑换券充值 支付宝
	* @param token
	 * @param member_id
	 * @param ticket 兑换券数量
	 * @param rate 折扣
	 * @param type 1充值 2升级
	 * @throws Exception 
	 */
	@RequestMapping(value="/rechargeTicketAliPay",method=RequestMethod.POST)
	public String rechargeTicketAliPay(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String ticket ,String rate, String pay_pwd, String type) throws NumberFormatException, Exception{
		
		//验证参数
		if (ticket == null || rate == null || type==null) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
			out.flush();
			out.close();
			return null;
		}
		if (!StringUtil.isNumeric(ticket) || !StringUtil.isRate(rate) ||  Integer.parseInt(ticket) > Integer.parseInt(configService.loadConfig("TICKET_BUY_MAXNUM")) ||( !"1".equals(type) && !"2".equals(type))||  Integer.parseInt(ticket) < 0) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		memberVO = memberService.getAllInfoById(member_id);
		//体验会员
		if("1".equals(memberVO.getExp_state())){
			memberVO.setLevel(PropertieUtil.loadPropertie("common_level"));
		}
		// 验证可享受充值优惠 验证充值数量大于折扣对应的起批量 1.充值 2升级
		boolean flag = false;
		if("1".equals(type)){
			List<MemberLevelItemVO> enjoy_privilege = memberLevelItemService.selectenjoyPrivilege(memberVO.getLevel());
			for (MemberLevelItemVO memberLevelItemVO : enjoy_privilege) {
				if (rate.equals(memberLevelItemVO.getRate())
						&& Integer.parseInt(memberLevelItemVO.getStart_ticket()) <= Integer.parseInt(ticket)) {
					flag = true;
					break;
				}
			}
		}else if("2".equals(type)){
			List<MemberLevelItemVO> advance_privilege = memberLevelItemService.selectadvancePrivilege(memberVO.getLevel(),member_id);
			for (MemberLevelItemVO memberLevelItemVO : advance_privilege) {
				if (rate.equals(memberLevelItemVO.getRate()) && ticket.equals(NumberUtil.formatDouble(Double.parseDouble(memberLevelItemVO.getNeed_price()) / Double.parseDouble(memberLevelItemVO.getRate()), 0))&& !PropertieUtil.loadPropertie("master_level").equals(memberLevelItemVO.getLevel())) {
					flag = true;
					break;
				}
			}
		}
		if (!flag) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		String price = "0";
		if("1".equals(type)){
			price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
		}else if("2".equals(type)){
			if(Integer.parseInt(ticket) * Double.parseDouble(rate) > 1){
				price = (int)(Double.parseDouble(Integer.parseInt(ticket) * Double.parseDouble(rate) + ""))+"";
			}else{
				price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
			}
		}
		
		String ticket_name = configService.loadConfig("TICKET_NAME");
		
		// 生成支付单 返回单号
		String no = payService.genPayOrder(3, price, ticket_name+"充值", 1, member_id);
		// 保存参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("ticket", ticket);
		map.put("rate", rate);
		map.put("lang", lang);
		payService.updatePayOrderParams(no, JSON.toJSONString(map));
		
		// 充值
		request.setAttribute("payType", 2);
		request.setAttribute("order_no", no);
		request.setAttribute("price", price);
		request.setAttribute("body", ticket_name+"充值");
		return "forward:aliPrePay";
	}
	
	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/ticketAliPayNotify",method=RequestMethod.POST)
	public void ticketAliPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in rechargeAliPayNotify--------------------------------------------");
		//解析参数
		Map<String,String> params = payService.resolveAliParam(request);
		System.out.println(params);
		if(params==null){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(403,"forbidden","","")) );
			out.flush();
			out.close();
			return;
		}
		// 判断签名是否正确  
		boolean flag = payService.checkAliParam(params);
		if(flag){
			//1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			//3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
			//4、验证app_id是否为该商户本身。
			//上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
			//在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
			//在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
			//检查  查询订单号码和价格是否和数据库匹配
			payVO =  payService.getPayOrderByNo(params.get("out_trade_no"));
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//			String p = payVO.getTotal_price();
//			payVO.setTotal_price("0.01");
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			if(payVO !=null && params.get("total_amount").equals(payVO.getTotal_price())&&ConfigUtil.ALIPAY_APP_ID.equals(params.get("app_id")) && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//				payVO.setTotal_price(p);
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
				//******************************支付成功业务逻辑start**************************************//
				//关联操作
				JSONObject obj = JSON.parseObject(payVO.getParams());
				//提货券充值 生成日志 修改支付状态
				String conn_no = payService.insertMemberTicket(payVO, payVO.getMember_id(), obj.getString("ticket"), obj.getString("rate"), 2, PropertieUtil.loadPropertie("partner_level"),"1");
				//分润
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				splitService.split(payVO.getMember_id(), memberVO.getLevel(), 1, obj.getString("ticket"), obj.getString("rate"), conn_no, 0+"", 2+"", "1");
				//充劵时分润推送
				pushService.rechargeTicket(conn_no,member_id);
				
				//******************************支付成功业务逻辑end**************************************//
			}else{
				//******************************支付失败业务逻辑start**************************************//
				//******************************支付失败业务逻辑end**************************************//
			}
		}
	}
	
	/**
	 * 兑换券充值 微信
	 * @param token
	 * @param member_id
	 * @param ticket 兑换券数量
	 * @param rate 折扣
	 * @param type 1充值 2升级
	 * @throws Exception 
	 */
	@RequestMapping(value="/rechargeTicketWechatPay",method=RequestMethod.POST)
	public String rechargeTicketWechatPay(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String ticket ,String rate, String pay_pwd, String type) throws NumberFormatException, Exception{
		// 验证参数
		if (ticket == null || rate == null || type == null) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
			out.flush();
			out.close();
			return null;
		}
		if (!StringUtil.isNumeric(ticket) || !StringUtil.isRate(rate)
				|| Integer.parseInt(ticket) > Integer.parseInt(configService.loadConfig("TICKET_BUY_MAXNUM"))
				|| (!"1".equals(type) && !"2".equals(type))||  Integer.parseInt(ticket) < 0) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		// 验证可享受充值优惠 验证充值数量大于折扣对应的起批量 1.充值 2升级
		memberVO = memberService.getAllInfoById(member_id);
		//体验会员
		if("1".equals(memberVO.getExp_state())){
			memberVO.setLevel(PropertieUtil.loadPropertie("common_level"));
		}
		boolean flag = false;
		if ("1".equals(type)) {
			List<MemberLevelItemVO> enjoy_privilege = memberLevelItemService.selectenjoyPrivilege(memberVO.getLevel());
			for (MemberLevelItemVO memberLevelItemVO : enjoy_privilege) {
				if (rate.equals(memberLevelItemVO.getRate())
						&& Integer.parseInt(memberLevelItemVO.getStart_ticket()) <= Integer.parseInt(ticket)) {
					flag = true;
					break;
				}
			}
		} else if ("2".equals(type)) {
			List<MemberLevelItemVO> advance_privilege = memberLevelItemService
					.selectadvancePrivilege(memberVO.getLevel(), member_id);
			for (MemberLevelItemVO memberLevelItemVO : advance_privilege) {
				if (rate.equals(memberLevelItemVO.getRate()) && ticket.equals(NumberUtil.formatDouble(Double.parseDouble(memberLevelItemVO.getNeed_price()) / Double.parseDouble(memberLevelItemVO.getRate()), 0))&& !PropertieUtil.loadPropertie("master_level").equals(memberLevelItemVO.getLevel())) {
					flag = true;
					break;
				}
			}
		}
		if (!flag) {
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
			out.flush();
			out.close();
			return null;
		}
		String ticket_name = configService.loadConfig("TICKET_NAME");
		
		String price = "0";
		if("1".equals(type)){
			price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
		}else if("2".equals(type)){
			if(Integer.parseInt(ticket) * Double.parseDouble(rate) > 1){
				price = (int)(Double.parseDouble(Integer.parseInt(ticket) * Double.parseDouble(rate) + ""))+"";
			}else{
				price = Integer.parseInt(ticket) * Double.parseDouble(rate) + "";
			}
		}
		//生成支付单 返回单号
		String no = payService.genPayOrder(3,price,ticket_name+"充值",2, member_id);
		//保存参数
		Map<String,String> map =new HashMap<String, String>();
		map.put("ticket", ticket);
		map.put("rate", rate);
		map.put("lang", lang);
		payService.updatePayOrderParams(no,JSON.toJSONString(map));
		

		
		//充值
		request.setAttribute("payType", 2);
		request.setAttribute("order_no", no);
		request.setAttribute("price", price);
		request.setAttribute("body", ticket_name+"充值");
		return "forward:wxPrePay";
		
	}

	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/ticketWechatPayNotify",method=RequestMethod.POST)
	public void ticketWechatPayNotify(
			@RequestHeader (value="AUTHORIZATION", required=false)String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			HttpServletRequest request, HttpServletResponse response,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		
		String result = null;
		//解析参数
		SortedMap<Object, Object> packageParams = payService.resolveWechatParam(request);
		System.out.println(packageParams);
		if(packageParams==null){
			result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[参数解析失败]]></return_msg>" + "</xml> ";
			System.out.println("参数解析失败");
		}
		// 判断签名是否正确  商户ID参数正确  
		if(result==null){
			result = payService.checkWechatParam(packageParams);
		}
		//执行业务逻辑   检查判断
		if(result == null){
			// 这里是支付成功
			// 执行自己的业务逻辑
			String mch_id = (String) packageParams.get("mch_id"); // 商户号
			String openid = (String) packageParams.get("openid"); // 用户标识
			String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
			String total_fee = (String) packageParams.get("total_fee"); //金额
			String transaction_id = (String) packageParams.get("transaction_id"); // 微信支付订单号
			
			//检查  查询订单号码和价格是否和数据库匹配
			payVO =  payService.getPayOrderByNo(out_trade_no);
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//			String p = payVO.getTotal_price();
//			payVO.setTotal_price("0.01");
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			if(payVO==null|| Integer.parseInt(total_fee) != new BigDecimal(payVO.getTotal_price()).multiply(new BigDecimal(100)).intValue() || !"N".equals(payVO.getPay_yn())){
				 System.out.println("支付失败,错误信息：" + "订单信息错误");
				 result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
			}else{
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				//******************************支付成功业务逻辑start**************************************//
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//				payVO.setTotal_price(p);
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
				//关联操作
				JSONObject obj = JSON.parseObject(payVO.getParams());
				//提货券充值 生成日志 修改支付状态
				String conn_no = payService.insertMemberTicket(payVO, payVO.getMember_id(), obj.getString("ticket"), obj.getString("rate"), 3, PropertieUtil.loadPropertie("partner_level"),"1");
				//分润
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				splitService.split(payVO.getMember_id(), memberVO.getLevel(), 1, obj.getString("ticket"), obj.getString("rate"), conn_no, 0+"", 3+"", "1");
				//充劵时分润推送
				pushService.rechargeTicket(conn_no,member_id);

				//******************************支付成功业务逻辑end**************************************//
				result = "success";
			}
		}
		
		//支付失败业务逻辑
		if(!"success".equals(result)){
			//******************************支付失败业务逻辑start**************************************//
			
			//******************************支付失败业务逻辑end**************************************//
		}else if("success".equals(result)){
			result = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
					+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
		}
		
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(result.getBytes());
		out.flush();
		out.close();
	}
	
	/**
	 * 兑换券充值 余额
	 * @param token
	 * @param member_id
	 * @param ticket 兑换券数量
	 * @param rate 折扣
	 * @param pay_pwd 支付密码
	 * @param type 1充值 2升级
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value="/rechargeTicketCashPay",method=RequestMethod.POST)
	public Object rechargeTicketCashPay(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="OS", required=false) String os, @RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String ticket ,String rate, String pay_pwd, String type) throws Exception{
		 
		//验证参数
		if(ticket==null  || rate ==null || type==null || (pay_pwd==null && !"admin".equals(os)) || "admin".equals(os) && member_id == null){
			return PackageUtil.packageParams(10001,"缺少必选参数","","");
		}
		if (!StringUtil.isNumeric(ticket) || !StringUtil.isRate(rate)
				|| Integer.parseInt(ticket) > Integer.parseInt(configService.loadConfig("TICKET_BUY_MAXNUM"))
				|| (!"1".equals(type) && !"2".equals(type))||  Integer.parseInt(ticket) < 0) {
			return PackageUtil.packageParams(10000,"参数不正确","","");
		}
		//验证支付密码
		if(!"admin".equals(os)){
			memberVO.setId(member_id);
			int total = memberService.chekPayPwd(memberVO);
			if(total == 0){
				return PackageUtil.packageParams(12005,"支付密码错误","","");
			}
		}
		//验证可享受充值优惠 验证充值数量大于折扣对应的起批量
		memberVO = memberService.getAllInfoById(member_id);
		//体验会员
		if("1".equals(memberVO.getExp_state())){
			memberVO.setLevel(PropertieUtil.loadPropertie("common_level"));
		}
		boolean flag = false;
		if ("1".equals(type)) {
			List<MemberLevelItemVO> enjoy_privilege = memberLevelItemService.selectenjoyPrivilege(memberVO.getLevel());
			for (MemberLevelItemVO memberLevelItemVO : enjoy_privilege) {
				if (rate.equals(memberLevelItemVO.getRate())
						&& Integer.parseInt(memberLevelItemVO.getStart_ticket()) <= Integer.parseInt(ticket)) {
					flag = true;
					break;
				}
			}
		} else if ("2".equals(type)) {
			List<MemberLevelItemVO> advance_privilege = memberLevelItemService
					.selectadvancePrivilege(memberVO.getLevel(), member_id);
			for (MemberLevelItemVO memberLevelItemVO : advance_privilege) {
				if (rate.equals(memberLevelItemVO.getRate()) && ticket.equals(NumberUtil.formatDouble(Double.parseDouble(memberLevelItemVO.getNeed_price()) / Double.parseDouble(memberLevelItemVO.getRate()), 0))&& !PropertieUtil.loadPropertie("master_level").equals(memberLevelItemVO.getLevel())) {
					flag = true;
					break;
				}
			}
		}
		if(!flag){
			return PackageUtil.packageParams(10000,"参数不正确","","");
		}
		
		//减掉余额 生成日志
		double price = 0;
		if("1".equals(type)){
			price = Integer.parseInt(ticket) * Double.parseDouble(rate);
		}else if("2".equals(type)){
			if(Integer.parseInt(ticket) * Double.parseDouble(rate) > 1){
				price = (int)(Double.parseDouble(Integer.parseInt(ticket) * Double.parseDouble(rate) + ""));
			}else{
				price = Integer.parseInt(ticket) * Double.parseDouble(rate);
			}
		}
		String country = "";
		if(lang != null && "en".equals(lang)){
			country = "0";
		}else{
			country = "1";
		}
		int re = 0;
		if("1".equals(country)){
			re = payService.subFreeCash(member_id, price, ticket, rate,country);
		}else if("0".equals(country)){
			re = payService.subFreeCashEn(member_id, price, ticket, rate,country);
		}
		if(re == 0){
			return PackageUtil.packageParams(10907,"余额不足","","");
		}else{
			//提货券充值 生成日志
			String conn_no = payService.insertMemberTicket(null,member_id, ticket, rate, 1, PropertieUtil.loadPropertie("partner_level"), country);
			//分润
			memberVO = memberService.getAllInfoById(member_id); 
			splitService.split(member_id, memberVO.getLevel(), 1, ticket, rate, conn_no,  0+"", 1+"", country);
			//充劵时分润推送
			
			if("1".equals(country)){
				pushService.rechargeTicket(conn_no,member_id);
			}else if("0".equals(country)){
				pushInterService.rechargeTicket(conn_no,member_id,country);
			}
			return PackageUtil.packageParams(200,"successs","",""); 
		}
	}
	
	/**
	 * 余额充值 PayssionPay
	 * @param token
	 * @param member_id
	 * @param free_cash 金额
	 * @throws Exception 
	 */
	/*@RequestMapping(value="/rechargeMoneyPayssionPay",method=RequestMethod.POST)
	public String rechargeMoneyPayssionPay(@RequestHeader (value="LANG", required=false) String lang,@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,CashRechargeVO rechargeVO, String pay_key) throws Exception{
		//验证参数
		if( free_cash==null||"".equals(free_cash) || lang==null || pay_key==null){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
			out.flush();
			out.close();
			return null;
		}
		//验证类型
		List<String> keyList = dicService.getChildNamesByParent(PropertieUtil.loadPropertie("payssion_key"));
		if(!StringUtil.isPrice(free_cash)||!keyList.contains(pay_key) || !"en".equals(lang.toLowerCase()) ){ 
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000,"参数错误，请参考API文档","","")));
			out.flush();
			out.close();
			return null;
		}
		//生成支付单 返回单号
		String no = payService.genPayOrder(2,free_cash,"余额充值",1, member_id);
		// 保存参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("lang", lang);
		map.put("payKey", pay_key);
		payService.updatePayOrderParams(no, JSON.toJSONString(map));
		//充值
		request.setAttribute("payType", 1);
		request.setAttribute("order_no", no);
		request.setAttribute("price", free_cash);
		request.setAttribute("body", "余额充值");
		request.setAttribute("payKey", pay_key);
		return "forward:payssionPrePay";
	}*/
	
	/**
	 * 回调PayssionPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/rechargePayssionPayNotify",method=RequestMethod.POST)
	public void rechargePayssionPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in ticketPayssionPayNotify--------------------------------------------");
		//解析参数
		Map<String,String> params = payService.resolveAPayssionParam(request);
		payVO =  payService.getPayOrderByNo(params.get("order_id"));
		// 判断签名是否正确  
		boolean flag = payService.checkPayssionParam(payVO, params);
		if (flag) {
			int re = payService.updateOrderPayFinish(payVO);
			if (re == 0) {
				return;
			}
			// ******************************支付成功业务逻辑start**************************************//
			// @@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			// payVO.setTotal_price(p);
			// @@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			moneyService.updateRechargeSuccessAndAddCashEn(payVO);

			// ******************************支付成功业务逻辑end**************************************//
		} else {
			// ******************************支付失败业务逻辑start**************************************//
			// ******************************支付失败业务逻辑end**************************************//
		}
	}
	
	/**
	 * 余额充值 微信
	 * @param token
	 * @param member_id
	 * @param free_cash 金额
	 * @throws IOException 
	 */
	@RequestMapping(value="/rechargeMoneyWechatPay",method=RequestMethod.POST)
	public String rechargeMoneyWechatPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,CashRechargeVO rechargeVO) throws IOException{
		
		//验证参数
		if( free_cash==null||"".equals(free_cash)){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
			out.flush();
			out.close();
			return null;
		}
		//验证类型
		if(!StringUtil.isPrice(free_cash)){ 
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000,"参数错误，请参考API文档","","")));
			out.flush();
			out.close();
			return null;
		}
		//生成支付单 返回单号
		String no = payService.genPayOrder(2,free_cash,"余额充值",2, member_id);
		//充值
		request.setAttribute("payType", 1);
		request.setAttribute("order_no", no);
		request.setAttribute("price", free_cash);
		request.setAttribute("body", "余额充值");
		return "forward:wxPrePay";
		
	}
	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/rechargeWechatPayNotify",method=RequestMethod.POST)
	public void rechargeWechatPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		
		String result = null;
		//解析参数
		SortedMap<Object, Object> packageParams = payService.resolveWechatParam(request);
		System.out.println(packageParams);
		if(packageParams==null){
			result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[参数解析失败]]></return_msg>" + "</xml> ";
			System.out.println("参数解析失败");
		}
		// 判断签名是否正确  商户ID参数正确  
		if(result==null){
			result = payService.checkWechatParam(packageParams);
		}
		//执行业务逻辑   检查判断
		if(result == null){
			// 这里是支付成功
			// 执行自己的业务逻辑
			String mch_id = (String) packageParams.get("mch_id"); // 商户号
			String openid = (String) packageParams.get("openid"); // 用户标识
			String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
			String total_fee = (String) packageParams.get("total_fee"); //金额
			String transaction_id = (String) packageParams.get("transaction_id"); // 微信支付订单号
			
			//检查  查询订单号码和价格是否和数据库匹配
			payVO =  payService.getPayOrderByNo(out_trade_no);
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//			String p = payVO.getTotal_price();
//			payVO.setTotal_price("0.01");
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			if(payVO==null|| Integer.parseInt(total_fee) != new BigDecimal(payVO.getTotal_price()).multiply(new BigDecimal(100)).intValue() || !"N".equals(payVO.getPay_yn())){
				 System.out.println("支付失败,错误信息：" + "订单信息错误");
				 result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
			}else{
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				//******************************支付成功业务逻辑start**************************************//
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//				payVO.setTotal_price(p);
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
				//关联操作
				moneyService.updateRechargeSuccessAndAddCash(payVO);
				//******************************支付成功业务逻辑end**************************************//
				result = "success";
			}
		}
		
		//支付失败业务逻辑
		if(!"success".equals(result)){
			//******************************支付失败业务逻辑start**************************************//
			
			//******************************支付失败业务逻辑end**************************************//
		}else if("success".equals(result)){
			result = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
					+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
		}
		
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(result.getBytes());
		out.flush();
		out.close();
	}
	
	/**
	 * 余额充值 支付宝
	 * @param token
	 * @param member_id
	 * @param free_cash 金额
	 * @throws IOException 
	 */
	@RequestMapping(value="/rechargeMoneyAliPay",method=RequestMethod.POST)
	public String rechargeMoneyAliPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,CashRechargeVO rechargeVO) throws IOException{
		//验证参数
		if( free_cash==null||"".equals(free_cash)){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
			out.flush();
			out.close();
			return null;
		}
		//验证类型
		if(!StringUtil.isPrice(free_cash)){ 
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10000,"参数错误，请参考API文档","","")));
			out.flush();
			out.close();
			return null;
		}
		
		//生成支付单 返回单号
		String no = payService.genPayOrder(2,free_cash,"余额充值",1, member_id);
		//充值
		request.setAttribute("payType", 1);
		request.setAttribute("order_no", no);
		request.setAttribute("price", free_cash);
		request.setAttribute("body", "余额充值");
		return "forward:aliPrePay";
	}
	
	/**
	 * 回调rechargeMoneyWechatPay
	 * @return
	 * @throws Exception 
	 */
	
	@RequestMapping(value="/rechargeAliPayNotify",method=RequestMethod.POST)
	public void rechargeAliPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in rechargeAliPayNotify--------------------------------------------");
		//解析参数
		Map<String,String> params = payService.resolveAliParam(request);
		System.out.println(params);
		if(params==null){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(403,"forbidden","","")) );
			out.flush();
			out.close();
			return;
		}
		// 判断签名是否正确  
		boolean flag = payService.checkAliParam(params);
		if(flag){
			//1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			//3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
			//4、验证app_id是否为该商户本身。
			//上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
			//在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
			//在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
			//检查  查询订单号码和价格是否和数据库匹配
			payVO =  payService.getPayOrderByNo(params.get("out_trade_no"));
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//			String p = payVO.getTotal_price();
//			payVO.setTotal_price("0.01");
			//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
			if(payVO !=null && params.get("total_amount").equals(payVO.getTotal_price())&&ConfigUtil.ALIPAY_APP_ID.equals(params.get("app_id")) && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				//******************************支付成功业务逻辑start**************************************//
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
//				payVO.setTotal_price(p);
				//@@@@@@@@@@@@@@@@@@@@@@@@@@@@待修改价格@@@@@@@@@@@@@@@@@@@@@@@@@@@@
				moneyService.updateRechargeSuccessAndAddCash(payVO);
				
				//******************************支付成功业务逻辑end**************************************//
			}else{
				//******************************支付失败业务逻辑start**************************************//
				//******************************支付失败业务逻辑end**************************************//
			}
		}
	}
	

	@ResponseBody
	@RequestMapping(value="/afterPayRetAddress",method=RequestMethod.GET)
	public Object afterPayRetAddress(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO,String order_pay_no) throws IOException{
		
		if(order_pay_no == null || "".equals(order_pay_no)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		String[] order_id_list = order_pay_no.split(",");
		String total_price= orderService.getTotalPriceByPayNo(order_id_list,member_id);
		OrderVO order = orderService.getOrderAddressByPayNo(order_id_list);
		if(order!=null){
			if(order.getPay_time()!=null&&order.getPay_time()!=""&&order.getPay_type()!=null&&order.getPay_type()!=""){
				map.put("adress_tel", order.getAddress_tel());
				map.put("adress_name", order.getAddress_name());
				map.put("adress_content", order.getAddress_content());
				map.put("address_tel", order.getAddress_tel());
				map.put("address_name", order.getAddress_name());
				map.put("address_content", order.getAddress_content());
				map.put("amount", total_price==null?0:total_price);
				map.put("state", "1");
			}else{
				map.put("adress_tel", order.getAddress_tel());
				map.put("adress_name", order.getAddress_name());
				map.put("adress_content", order.getAddress_content());
				map.put("address_tel", order.getAddress_tel());
				map.put("address_name", order.getAddress_name());
				map.put("address_content", order.getAddress_content());
				map.put("amount", total_price==null?0:total_price);
				map.put("state", "2");
			}
			
		}else{
			order = new OrderVO();
			return PackageUtil.packageParams(10905,"订单不存在","","");
		}

		return PackageUtil.packageParams(200,"successs",map,"");
		
	}
	//refund_type 0  取消订单 1退货
	@ResponseBody
	@RequestMapping(value="/orderRefundWechat",method=RequestMethod.POST)
	public Object orderRefundWechat(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO,String refund_id,String out_refund_no, String out_trade_no, String refund_fee,
			String total_fee,String refund_type,String order_id,String total_ticket) throws Exception{
		
		OrderVO order = orderService.getOrderById(order_id);
		OrderPayVO payVO =  payService.getPayOrderByNo(out_trade_no);
		JSONObject obj = JSON.parseObject(payVO.getParams());
		String trade_type = "APP";
		if(obj.get("trade_type")!=null){
			if("JSAPI".equals(obj.get("trade_type").toString())){
				trade_type = "JSAPI";
			}
		}
		System.out.println("**********************************"+refund_fee);
		System.out.println("**********************************"+total_fee);
		String result = payService.wechatRefund(request,out_trade_no, out_refund_no, total_fee, refund_fee,trade_type);
		Map<String, String> map = XMLUtil.doXMLParse(result);
		if(map.get("return_code").equals("SUCCESS")&&out_refund_no.equals(map.get("out_refund_no"))&&out_trade_no.equals(map.get("out_trade_no"))&&total_fee.equals(map.get("total_fee"))&&refund_fee.equals(map.get("refund_fee"))){
			
			
			//没有使用兑换券
			if("0".equals(order.getTicket_status())){
				
				//部分退款
				if("0".equals(refund_type)){
					splitService.payBack(order_id, "2", order.getCreate_by(), 
							String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100), 
							null);
				} 
				//全部退款
				else if("1".equals(refund_type)){
					splitService.payBack(order_id, "2", order.getCreate_by(), 
							String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), 
							null);
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
			}
			
			
			//使用兑换券
			else if("1".equals(order.getTicket_status())){
				
				//部分退款
				if("0".equals(refund_type)){
					splitService.deleteTicketBuyAndGenBackLog(
							order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"2",
							String.valueOf(Double.parseDouble(refund_fee)/100==0?"0":Double.parseDouble(refund_fee)/100),
							null);
				} 
				//全部退款
				else if("1".equals(refund_type)){
					splitService.payBackUseTicket(order_id,"2",order.getCreate_by(),
							String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),
							null);
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
				
			}
			
			return PackageUtil.packageParams(200,"successs",map,"");
		}else{
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
	}
	//refund_type 0订单取消退款  1 退货退款
	@ResponseBody
	@RequestMapping(value="/orderRefundAlipay",method=RequestMethod.POST)
	public Object orderRefundAlipay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO,String refund_id,String out_refund_no, String out_trade_no, String total_fee,
			String refund_fee,String refund_type,String order_id,String total_ticket) throws Exception{
		//退款
		AlipayTradeRefundResponse re = payService.alipayRefund(out_trade_no, out_refund_no, total_fee, refund_fee);
		
		OrderVO order = orderService.getOrderById(order_id);
		

		if(re.isSuccess()&&out_trade_no.equals(re.getOutTradeNo())){
				
			//沒有使用兑换券
			if("0".equals(order.getTicket_status())){
				//全部退款
				if("0".equals(refund_type)){
					splitService.payBack(order_id, "1", order.getCreate_by(), 
							String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())), 
							null);
					
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
				}
				//部分退款
				else if("1".equals(refund_type)){
					splitService.payBack(order_id, "1", order.getCreate_by(), 
							refund_fee, 
							null);
				}
				
			}
			
			//使用兑换券
			else if("1".equals(order.getTicket_status())){
				//部分退款
				if("1".equals(refund_type)){
					splitService.deleteTicketBuyAndGenBackLog(
							order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"1",
							refund_fee,
							null);
				} 
				//全部退款
				else if("0".equals(refund_type)){
					splitService.payBackUseTicket(order_id,"1",order.getCreate_by(),
							String.valueOf(Double.parseDouble(order.getTotal_price())+Double.parseDouble(order.getFreight())),
							null);	
					
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
					
				}
		
			}
			
			return PackageUtil.packageParams(200,"successs",re,"");
		}else{
			return PackageUtil.packageParams(10917,"退款异常","","");
		}
	}
	
	@ResponseBody
	@RequestMapping(value="/orderRefund",method=RequestMethod.POST)
	public Object orderRefund(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO,String refund_type,String order_id,String ret_amount,String total_ticket) throws Exception{
		
			OrderVO order = orderService.getOrderById(order_id);
			
			System.out.println("余额退款");
			System.out.println(refund_type);
			System.out.println(order_id);
			System.out.println(ret_amount);
			System.out.println(total_ticket);
			
			System.out.println(")))"+order.getCancel_state());
			System.out.println(")))"+order.getState());
			//没有使用 购物券
			if("0".equals(order.getTicket_status())){
				//部分退 没花卷
				if("1".equals(refund_type)){
					//购物专用金
					if("4".equals(order.getPay_type())){
						splitService.payBack(order_id, "4", order.getCreate_by(), 
								null, 
								ret_amount);
					}
					//余额购买
					else if("3".equals(order.getPay_type())){
						splitService.payBack(order_id, "3", order.getCreate_by(), 
								ret_amount, 
								null);
					}
				}
				//全退 没花卷
				else if("0".equals(refund_type)){
					//购物专用金
					if("4".equals(order.getPay_type())){
						splitService.payBack(order_id, "4", order.getCreate_by(), 
								null, 
								ret_amount);
					}
					//余额购买
					else if("3".equals(order.getPay_type())){
						splitService.payBack(order_id, "3", order.getCreate_by(), 
								ret_amount, 
								null);
					}
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
					
				}
				
				// 交易退款 price 购买钱数 buy_cash 购物专用金 二选一 pay_type(兑换券,订单表的pay_type)
				
			}
			
			//使用 购物券
			else if("1".equals(order.getTicket_status())){
				
				//部分退款
				if("1".equals(refund_type)){
					//String member_id, int num, String order_id,String pay_type, String price, String buy_cash
					//余额 购买时
					if(order.getPay_type().equals("3")){
						splitService.deleteTicketBuyAndGenBackLog(
								order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"3",ret_amount,null);
					}
					//购物专用金购买时
					else if(order.getPay_type().equals("4")){
						splitService.deleteTicketBuyAndGenBackLog(
								order.getCreate_by(), Integer.parseInt(total_ticket), order_id,"4",null,ret_amount);	
					}
					
				}
				//全退
				else{
					
					//余额 购买时
					if(order.getPay_type().equals("3")){
						splitService.payBackUseTicket(order_id,"3",order.getCreate_by(),
								ret_amount,
								null);
					}
					//购物专用金购买时
					else if(order.getPay_type().equals("4")){
						splitService.payBackUseTicket(order_id,order.getPay_type(),order.getCreate_by(),
								null,
								ret_amount);	
					}
					
					//商家取消订单时推送
					if("1".equals(order.getCancel_state())){
						sendCancelOrderPush(order.getCreate_by(),order.getNo());
					}
					
				}
					
			}
			
			return PackageUtil.packageParams(200,"successs","","");
	}
	
	/**
	 *  支付宝购买套餐
	 * @param token
	 * @param member_id
	 * @param request
	 * @param response
	 * @param memberVO
	 * @param package_id
	 * @param address_id
	 * @param standard_id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/packageAliPay",method=RequestMethod.POST)
	public String packageAliPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,
			@RequestHeader (value="LANG", required=false) String lang,
			String pay_key,
			HttpServletRequest request, HttpServletResponse response
			,String package_id,String address_id,String standard_id) throws IOException{
		
		if( package_id==null||"".equals(package_id)||standard_id==null||"".equals(standard_id)||address_id==null||"".equals(address_id)){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
			out.flush();
			out.close();
			return null;
		}
		//money  order_id order_pay_no
		int packageCount = memberCartServise.getPackageCountByMemberId(member_id);
		if(packageCount>0){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10922,"套餐已购买","","")));
			out.flush();
			out.close();
			return null;
		}
		
		
		try {
			List<String> keyList = dicService.getChildNamesByParent(PropertieUtil.loadPropertie("payssion_key"));
			if (!keyList.contains(pay_key) || !"en".equals(lang.toLowerCase())) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
				out.flush();
				out.close();
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		AddressVO addressVO = memberCartServise.getMemberAddressById(address_id);
		if(addressVO==null){
			addressVO = new AddressVO();
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10901,"收货地址错误",addressVO,"")));
			out.flush();
			out.close();
			return null;
			 
		}
		PackageVO pack = new PackageVO();
		
			int check = payService.checkPackage(package_id,standard_id);
			if(check==0){
				if(check==0){
					response.setContentType("text/json;charset=utf-8");   
					PrintWriter out = response.getWriter(); 
					out.print(JSON.toJSONString(PackageUtil.packageParams(10202,"套餐不存在","","")));
					out.flush();
					out.close();
					return null;
				}
			}	
		//查询套餐
		pack = memberService.getGoodPackage(package_id,standard_id);
		
		if(pack==null){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10202,"套餐不存在","","")));
			out.flush();
			out.close();
			return null;
		}
		
		if(Integer.parseInt(pack.getNum())<1){
			//库存不够
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10909,"库存不足","","")));
			out.flush();
			out.close();
			return null;
		}
		String no = payService.genPayOrder(1,pack.getPrice(),"支付宝套餐支付",1, member_id);
		
		String os =  request.getHeader("OS");
		String order_from   = "1";
		if (os != null) {
			os = os.toLowerCase();
		}
		if("wechat".equals(os)){
			order_from = "2";
		}
		else if("web".equals(os)){
			order_from = "3";
		}
		else if("ios".equals(os)||"android".equals(os)){
			order_from = "1";
		}
		
		
		Map<String,String> map =new HashMap<String, String>();
		map.put("order_pay_no", no);
		map.put("ticket", "0");
		map.put("price", pack.getPrice());
		map.put("freight", "0");
		map.put("join_cash", pack.getJoin_cash());
		map.put("address_id", address_id);
		map.put("package_id", package_id);
		map.put("order_from",order_from);
		map.put("lang", lang);
		map.put("payKey", pay_key);
		if(standard_id==null||"".equals(standard_id)){
			map.put("standard_id", pack.getGood_standard_id());
		}else{
			map.put("standard_id", standard_id);
		}
		
		payService.updatePayOrderParams(no,JSON.toJSONString(map));
		
		//套餐购买
		request.setAttribute("payType", 4);
		request.setAttribute("order_no", no);
		request.setAttribute("price", pack.getPrice());
		request.setAttribute("body", "购买套餐");
		
		return "forward:aliPrePay";
	}
	
	
	@RequestMapping(value="/packageAliPayNotify",method=RequestMethod.POST)
	public void packageAliPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, OrderPayVO payVO) throws Exception{
		System.out.println("-------------------------------come in rechargeAliPayNotify--------------------------------------------");
		//解析参数
		Map<String,String> params = payService.resolveAliParam(request);
		System.out.println(params);
		if(params==null){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(403,"forbidden","","")) );
			out.flush();
			out.close();
			return;
		}
		// 判断签名是否正确  
		boolean flag = payService.checkAliParam(params);
		if(flag){
			//1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			//2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			//3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email），
			//4、验证app_id是否为该商户本身。
			//上述1、2、3、4有任何一个验证不通过，则表明本次通知是异常通知，务必忽略。
			//在上述验证通过后商户必须根据支付宝不同类型的业务通知，正确的进行不同的业务处理，并且过滤重复的通知结果数据。
			//在支付宝的业务通知中，只有交易通知状态为TRADE_SUCCESS或TRADE_FINISHED时，支付宝才会认定为买家付款成功。
			//检查  查询订单号码和价格是否和数据库匹配
		//	payVO =  payService.getPayOrderByNo(params.get("out_trade_no"));
			
			payVO =  payService.getPayOrderByNo(params.get("out_trade_no"));
			System.out.println("支付宝套餐支付回调"+params.get("out_trade_no"));
			System.out.println("支付宝套餐支付回调"+payVO.getNo());
			System.out.println("支付宝套餐支付回调"+payVO.getId());
			
			if(payVO !=null && params.get("total_amount").equals(payVO.getTotal_price())&&ConfigUtil.ALIPAY_APP_ID.equals(params.get("app_id")) && "N".equals(payVO.getPay_yn())){
				//******************************支付成功业务逻辑start**************************************//
				//&& "N".equals(payVO.getPay_yn())
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
	
				System.out.println("支付宝套餐支付回调进入IF"+params.get("out_trade_no"));
				System.out.println("支付宝套餐支付回调进入IF"+payVO.getNo());
				System.out.println("支付宝套餐支付回调进入IF"+payVO.getId());
				
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String ticket = obj.get("ticket").toString();
				String price = obj.get("price").toString();
				String join_cash = obj.get("join_cash").toString();
				String address_id = obj.get("address_id").toString();
				String package_id = obj.get("package_id").toString();
				String standard_id = obj.get("standard_id").toString();
				String order_from = obj.get("order_from").toString();
				String lang = obj.get("lang").toString();
				String country = "";
				if(lang==null){
					country = "1";
				}
				else if(lang.equals("en")){
					country = "0";
				}
				
				String conn_pay_id = payVO.getId();
				PackageVO pack = memberService.getGoodPackage(package_id,standard_id);
				AddressVO addressVO = memberCartServise.getMemberAddressById(address_id);
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				payVO.setPay_type("2");
				payService.insertPackage1(pack,memberVO,addressVO,"1",conn_pay_id, payVO,order_from,country);
				
				//******************************支付成功业务逻辑end**************************************//
			}else{
				//******************************支付失败业务逻辑start**************************************//
				//******************************支付失败业务逻辑end**************************************//
			}
		}
	}
	
	/**
	 *  微信购买套餐
	 * @param token
	 * @param member_id
	 * @param request
	 * @param response
	 * @param memberVO
	 * @param package_id
	 * @param address_id
	 * @param standard_id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/packageWxPay",method=RequestMethod.POST)
	public String packageWxPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)  String member_id,
			@RequestHeader (value="LANG", required=false) String lang,
			String pay_key,
			HttpServletRequest request, HttpServletResponse response
			,String package_id,String address_id,String standard_id) throws IOException{
		
		//验证参数
		if( package_id==null||"".equals(package_id)||standard_id==null||"".equals(standard_id)|| address_id==null||"".equals(address_id)){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
			out.flush();
			out.close();
			return null;
		}
				
		int packageCount = memberCartServise.getPackageCountByMemberId(member_id);
		if(packageCount>0){
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10922,"套餐已购买","","")));
			out.flush();
			out.close();
			return null;
		}
		
		AddressVO addressVO = memberCartServise.getMemberAddressById(address_id);
		if(addressVO==null){
			addressVO = new AddressVO();
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10901,"收货地址错误",addressVO,"")));
			out.flush();
			out.close();
			return null;
			 
		}
		PackageVO pack = new PackageVO();
		
			int check = payService.checkPackage(package_id,standard_id);
			if(check==0){
				if(check==0){
					response.setContentType("text/json;charset=utf-8");   
					PrintWriter out = response.getWriter(); 
					out.print(JSON.toJSONString(PackageUtil.packageParams(10202,"套餐不存在","","")));
					out.flush();
					out.close();
					return null;
				}
			}	
		//查询套餐
		pack = memberService.getGoodPackage(package_id,standard_id);
		
		
		
		if(Integer.parseInt(pack.getNum())<1){
			//库存不够
			response.setContentType("text/json;charset=utf-8");   
			PrintWriter out = response.getWriter(); 
			out.print(JSON.toJSONString(PackageUtil.packageParams(10909,"库存不足","","")));
			out.flush();
			out.close();
			return null;
		}
		
		String no = payService.genPayOrder(1,pack.getPrice(),"微信套餐支付",1, member_id);
		
		String os =  request.getHeader("OS");
		String order_from   = "1";
		if (os != null) {
			os = os.toLowerCase();
		}
		if("wechat".equals(os)){
			order_from = "2";
		}
		else if("web".equals(os)){
			order_from = "3";
		}
		else if("ios".equals(os)||"android".equals(os)){
			order_from = "1";
		}
		
		Map<String,String> map =new HashMap<String, String>();
		map.put("order_pay_no", no);
		map.put("ticket", pack.getTicket());
		map.put("price", pack.getPrice());
		map.put("freight", "0");
		map.put("join_cash", pack.getJoin_cash());
		map.put("address_id", address_id);
		map.put("package_id", package_id);
		map.put("order_from",order_from);
		map.put("lang", lang);
		map.put("payKey", pay_key);
		
		if(standard_id==null||"".equals(standard_id)){
			map.put("standard_id", pack.getGood_standard_id());
		}else{
			map.put("standard_id", standard_id);
		}
		
		payService.updatePayOrderParams(no,JSON.toJSONString(map));
		
		//套餐购买
		request.setAttribute("payType", 4);
		request.setAttribute("order_no", no);
		request.setAttribute("price", pack.getPrice());
		request.setAttribute("body", "购买套餐");
		return "forward:wxPrePay";
		
	}
	
	
	@RequestMapping(value="/packageWxPayNotify",method=RequestMethod.POST)
	public void packageWxPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
			,MemberVO memberVO, OrderPayVO payVO) throws Exception{
		
		String result = null;
		//解析参数
		SortedMap<Object, Object> packageParams = payService.resolveWechatParam(request);
		System.out.println(packageParams);
		if(packageParams==null){
			result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[参数解析失败]]></return_msg>" + "</xml> ";
			System.out.println("参数解析失败");
		}
		// 判断签名是否正确  商户ID参数正确  
		if(result==null){
			result = payService.checkWechatParam(packageParams);
		}
		//执行业务逻辑   检查判断
		if(result == null){
			// 这里是支付成功
			// 执行自己的业务逻辑
			String mch_id = (String) packageParams.get("mch_id"); // 商户号
			String openid = (String) packageParams.get("openid"); // 用户标识
			String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
			String total_fee = (String) packageParams.get("total_fee"); //金额
			String transaction_id = (String) packageParams.get("transaction_id"); // 微信支付订单号
			
			String lang = (String) packageParams.get("lang").toString();
			String country = "";
			if(lang==null){
				country = "1";
			}
			else if(lang.equals("en")){
				country = "0";
			}
			//检查  查询订单号码和价格是否和数据库匹配
			
			payVO =  payService.getPayOrderByNo(packageParams.get("out_trade_no").toString());
			if(payVO==null|| Integer.parseInt(total_fee) != new BigDecimal(payVO.getTotal_price()).multiply(new BigDecimal(100)).intValue()  || !"N".equals(payVO.getPay_yn())){
				 System.out.println("支付失败,错误信息：" + "订单信息错误");
				 result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
							+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
			}else{
				//******************************支付成功业务逻辑start**************************************//
				//关联操作
				/*JSONObject obj = JSON.parseObject(payVO.getParams());
				//提货券充值 生成日志 修改支付状态
				payService.insertMemberTicket(payVO, payVO.getMember_id(), obj.getString("ticket"), obj.getString("rate"), 3);
				//分润
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				splitService.split(payVO.getMember_id(), memberVO.getLevel(), 1, obj.getString("ticket"), obj.getString("rate"), null, 0+"", 3+"");
				
				packageLog.setState("0");
				packageLog.setRemark("付款成功");
				payService.updLogPackage(packageLog);*/
				
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String ticket = obj.get("ticket").toString();
				String price = obj.get("price").toString();
				String join_cash = obj.get("join_cash").toString();
				String address_id = obj.get("address_id").toString();
				String package_id = obj.get("package_id").toString();
				String standard_id = obj.get("standard_id").toString();
				String order_from = obj.get("order_from").toString();
				String conn_pay_id = payVO.getId();
				PackageVO pack = memberService.getGoodPackage(package_id,standard_id);
				AddressVO addressVO = memberCartServise.getMemberAddressById(address_id);
			
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				payVO.setPay_type("3");
				payService.insertPackage1(pack,memberVO,addressVO,"2",conn_pay_id,payVO,order_from,country);
				
				//splitJoinAward(payVO.getMember_id(), package_id);
				
				//******************************支付成功业务逻辑end**************************************//
				result = "success";
			}
		}
		
		//支付失败业务逻辑
		if(!"success".equals(result)){
			//******************************支付失败业务逻辑start**************************************//
			
			//******************************支付失败业务逻辑end**************************************//
		}else if("success".equals(result)){
			result = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
					+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
		}
		
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(result.getBytes());
		out.flush();
		out.close();
	}
	
	//入会奖分润
	private void splitJoinAward(String member_id, String package_id) throws Exception {
		//int total_can_use_ticket = memberCartVOMapper.getCanUseTicket(member_id);
		int ticket = payService.getToTalPackageTicket(package_id);
		int join_award = payService.getToTalPackageAward(package_id);
		if(ticket == 0 && join_award != 0){
			//只产生入会奖
			MemberVO memberVO = memberService.getAllInfoById(member_id);
			splitService.splitJoinAward(member_id, memberVO.getLevel(), 3, String.valueOf(ticket), "1", null, join_award+"", 1+"");
		}else if(ticket!=0){
			//分润
			MemberVO memberVO = memberService.getAllInfoById(member_id);
			splitService.split(member_id, memberVO.getLevel(), 3, String.valueOf(ticket), "1", null, join_award+"", 1+"",null);
		}
	}
	
	public void sendCancelOrderPush(String member_id,String order_no){
		/*Map map = new HashMap();
		map.put("title", configService.loadConfig("APP_NAME"));
		map.put("content", "订单"+order_no+"已取消");
		map.put("type", 5);
		//PushUtil.getuiPushSingle(memberService.getCidById(member_id), configService.loadConfig("APP_LOGO"), configService.loadConfig("APP_NAME"),
				"订单"+order_no+"已取消", "",JSON.toJSONString(map));*/
		pushService.sendCancelOrderPush(member_id,order_no);
		/*
		 	notice_num    1
			sys_num         2
			ems_num       3
			cash_num      4
			praise_num    5
		*/
		messageService.updMemberMsg(member_id,"2");
	}
	
	/**
	    * 支付宝订单支付
	    * @param token
	    * @param member_id
	    * @param request
	    * @param response
	    * @param memberVO
	    * @param order_pay_no
	    * @return
	    * @throws Exception
	    */
		@RequestMapping(value="/OrderAliPay",method=RequestMethod.POST)
		public Object OrderAliPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO,String order_pay_no) throws Exception{
			String[] order_id_List = order_pay_no.split(",");
			//验证参数
			if( order_id_List==null||"".equals(order_id_List)){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
				out.flush();
				out.close();
				return null;
			}
			String money = orderService.getTotalPriceByPayNo(order_id_List,member_id);
			//验证类型
			if(!StringUtil.isPrice(money)){ 
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10000,"参数错误，请参考API文档","","")));
				out.flush();
				out.close();
				return null;
			}
			
			int payStateCount = orderService.checkOrderPayState(order_id_List);
			if(payStateCount!=order_id_List.length){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			//付款时间倒计时暂停
			int payCount = orderService.stopOrderPayTimerByPayNo(order_id_List);
			if(payCount==0){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			
			//生成支付单 返回单号
			String no = payService.genPayOrder(1,money,"支付宝订单支付",1, member_id);
			
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", order_pay_no);
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			//购买订单
			request.setAttribute("payType", 3);
			request.setAttribute("order_no", no);
			request.setAttribute("price", money);
			request.setAttribute("body", "【在线支付订单】"+no);
			
			return "forward:aliPrePay";
		}
		
		/**
		 * 支付宝订单支付回调
		 * @param token
		 * @param member_id
		 * @param request
		 * @param response
		 * @param memberVO
		 * @param payVO
		 * @throws Exception
		 */
		@RequestMapping(value="/OrderAliPayNotify",method=RequestMethod.POST)
		public void OrderAliPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, OrderPayVO payVO) throws Exception{
			System.out.println("进入新的订单回调*********************************************************************");
			//解析参数
			Map<String,String> params = payService.resolveAliParam(request);
			System.out.println(params);
			if(params==null){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(403,"forbidden","","")) );
				out.flush();
				out.close();
				return;
			}
			// 判断签名是否正确  
			boolean flag = payService.checkAliParam(params);
			System.out.println("支付宝回调FLG"+flag);
			if(!flag){
				return;
			}
			payVO =  payService.getPayOrderByNo(params.get("out_trade_no"));
			
			
			if(payVO !=null && params.get("total_amount").equals(payVO.getTotal_price())&&ConfigUtil.ALIPAY_APP_ID.equals(params.get("app_id")) && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String order_id = (String) obj.get("order_pay_no");
				String[] order_id_list = order_id.split(",");
				//实际要付款的订单ID
				List<String> order_id_array =  orderService.getRealPayOrderId(order_id_list);
				//业务处理___________________________________________
				if(order_id_array!=null&&order_id_array.size()>0){
					//修改包裹状态
					uorderPayService.updOrderAndCaseAfterUnnormalPay("1",payVO.getId(),order_id_array);
					//order_pay  state 2  
					payService.updatePayOrderState1("2",payVO.getId());
					//delete order_timer 
					payService.delOrderTimer(order_id_list);
					//log_order
					for (int i = 0; i < order_id_array.size(); i++) {
						LogOrder log = new LogOrder();
						log.setOrder_id(order_id_array.get(i));
						log.setMember_id(payVO.getMember_id());
						log.setRemark("成功付款");
						orderService.InsertLogOrder(log);
					}
					MemberVO member= memberService.getAllInfoById(payVO.getMember_id());
					//分润
					benifitAfterOrderPay(order_id_list,member);
					
					order_id_list = new String[order_id_array.size()];
		 			for (int i = 0; i < order_id_array.size(); i++) {
		 				order_id_list[i]= order_id_array.get(i);
		 			}
		 			//订单支付推送
		 			List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_list);
		 			String country =orderList.get(0).getCountry();
		 			if("1".equals(country)){
		 				pushService.pushOrderPay(orderList);
		 			}else{
		 				pushInterService.pushOrderPay(orderList,country);
		 			}
		 			
				}
			}
		}
		
		 /**
	     * 支付订单以后 分润
	     * @throws Exception 
	     */
	    public void benifitAfterOrderPay(String[] order_id_List,MemberVO memberVO) throws Exception{
	    	List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_List);
			if(orderList!=null&&orderList.size()>0){
				for (int i = 0; i < orderList.size(); i++) {
					OrderVO oneOrder = orderList.get(i);
					String total_ticket = "";
					String country = orderList.get(i).getCountry();
					total_ticket = orderService.getToTalStandardTicket(oneOrder.getId());
					if(!"4".equals(oneOrder.getPay_type())){
						//没有使用兑换券
						if("0".equals(oneOrder.getTicket_status())){
							splitService.split(memberVO.getId(), memberVO.getLevel(), 2, total_ticket, oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null,null);
							if(Integer.parseInt(total_ticket)==0&&Double.parseDouble(oneOrder.getJoin_cash())>0){	
								splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket,oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null);
							}
						}
						//使用了兑换券
						else{
							if(Double.parseDouble(oneOrder.getJoin_cash())>0){	
									splitService.splitJoinAward(memberVO.getId(), memberVO.getLevel(), 2, total_ticket,oneOrder.getMember_rate(), oneOrder.getId(), oneOrder.getJoin_cash(), null);
							}
						}
						//oneOrder.getId() 只买东西时分润推送
						  if("1".equals(country)){
							  pushService.BuyGoodsProfit(oneOrder.getId());
				          }else{
				             pushInterService.BuyGoodsProfit(oneOrder.getId(),country);
				          }
						
					}
					
				}
			}
	    }
	    /**
		 * 订单微信支付
		 * @param token
		 * @param os
		 * @param member_id
		 * @param request
		 * @param response
		 * @param memberVO
		 * @param order_pay_no
		 * @return
		 * @throws IOException
		 */
		@RequestMapping(value="/OrderWxPay",method=RequestMethod.POST)
		public String OrderWxPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="OS", required=false) String os,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String order_pay_no) throws IOException{
			
			String[] order_id_List = order_pay_no.split(",");
			if (order_id_List == null || "".equals(order_id_List)  ) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
				out.flush();
				out.close();
				return null;
			}
			
			String money = orderService.getTotalPriceByPayNo(order_id_List,member_id);
			if (!StringUtil.isPrice(money)) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
				out.flush();
				out.close();
				return null;
			}
			int payStateCount = orderService.checkOrderPayState(order_id_List);
			if(payStateCount!=order_id_List.length){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			//付款时间倒计时暂停
			int payCount = orderService.stopOrderPayTimerByPayNo(order_id_List);
			if(payCount==0){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			
			memberVO = memberService.getAllInfoById(member_id);
			String no = payService.genPayOrder(1,money,"微信订单支付",2, member_id);
			//保存参数
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", order_pay_no);
			if("wechat".equals(os)){
				map.put("trade_type", "JSAPI");
			}else if("android".equals(os)||"ios".equals(os)){
				map.put("trade_type", "APP");
			}
			
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			//订单支付
			request.setAttribute("payType", 3);
			request.setAttribute("order_no", no);
			request.setAttribute("price", money);
			request.setAttribute("body", "【在线支付订单】"+no);
			return "forward:wxPrePay";
		}
		
		/**
		 * 微信订单支付回调
		 * @param token
		 * @param member_id
		 * @param request
		 * @param response
		 * @param memberVO
		 * @param payVO
		 * @throws Exception
		 */
		@RequestMapping(value="/OrderWxPayNotify",method=RequestMethod.POST)
		public void OrderWxPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO,OrderPayVO payVO) throws Exception{
			
			String result = null;
			//解析参数
			SortedMap<Object, Object> packageParams = payService.resolveWechatParam(request);
			System.out.println(packageParams);
			if(packageParams==null){
				result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[参数解析失败]]></return_msg>" + "</xml> ";
				System.out.println("参数解析失败");
			}
			// 判断签名是否正确  商户ID参数正确  
			if(result==null){
				result = payService.checkWechatParam(packageParams);
			}
			//执行业务逻辑   检查判断
			if(result == null){
				// 这里是支付成功
				// 执行自己的业务逻辑
				String mch_id = (String) packageParams.get("mch_id"); // 商户号
				String openid = (String) packageParams.get("openid"); // 用户标识
				String out_trade_no = (String) packageParams.get("out_trade_no"); // 商户订单号
				String total_fee = (String) packageParams.get("total_fee"); //金额
				String transaction_id = (String) packageParams.get("transaction_id"); // 微信支付订单号
				
				//检查  查询订单号码和价格是否和数据库匹配
				payVO =  payService.getPayOrderByNo(out_trade_no);

				if(payVO==null|| Integer.parseInt(total_fee) != new BigDecimal(payVO.getTotal_price()).multiply(new BigDecimal(100)).intValue() || !"N".equals(payVO.getPay_yn())){
					 System.out.println("支付失败,错误信息：" + "订单信息错误");
					 result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
								+ "<return_msg><![CDATA[参数错误]]></return_msg>" + "</xml> ";
				}else{
					int re = payService.updateOrderPayFinish(payVO);
					if(re==0){
						return;
					}
					//******************************支付成功业务逻辑start**************************************//
					System.out.println("********************************************OrderPayId"+payVO.getId());
					JSONObject obj = JSON.parseObject(payVO.getParams());
					String order_id = (String) obj.get("order_pay_no");
					String[] order_id_list = order_id.split(",");
					List<String> order_id_array =  orderService.getRealPayOrderId(order_id_list);
					//业务
					if(order_id_array!=null&&order_id_array.size()>0){
						//修改包裹状态
						uorderPayService.updOrderAndCaseAfterUnnormalPay("2",payVO.getId(),order_id_array);
						//order_pay  state 2  
						payService.updatePayOrderState1("2",payVO.getId());
						//delete order_timer 
						payService.delOrderTimer(order_id_list);
						
						for (int i = 0; i < order_id_array.size(); i++) {
							LogOrder log = new LogOrder();
							log.setOrder_id(order_id_array.get(i));
							log.setMember_id(payVO.getMember_id());
							log.setRemark("成功付款");
							orderService.InsertLogOrder(log);
						}
						MemberVO member= memberService.getAllInfoById(payVO.getMember_id());
						//分润
						benifitAfterOrderPay(order_id_list,member);
						
						order_id_list = new String[order_id_array.size()];
			 			for (int i = 0; i < order_id_array.size(); i++) {
			 				order_id_list[i]= order_id_array.get(i);
			 			}
			 			//订单支付推送
			 			List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_list);
			 			pushService.pushOrderPay(orderList);
			 			
					}else{
						return ;
					}
					//******************************支付成功业务逻辑end**************************************//
					result = "success";
				}
			}
			//支付失败业务逻辑
			if(!"success".equals(result)){
				//******************************支付失败业务逻辑start**************************************//
				
				//******************************支付失败业务逻辑end**************************************//
			}else if("success".equals(result)){
				result = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(result.getBytes());
			out.flush();
			out.close();
		}	
		
		/**
		 *  购买套餐 (余额 购物专用金)
		 * @param token
		 * @param member_id
		 * @param package_id
		 * @param address_id
		 * @param pay_pwd
		 * @param standard_id
		 * @param request
		 * @return
		 * @throws Exception
		 */
		@ResponseBody
		@RequestMapping(value="/packagePay",method=RequestMethod.POST)
		public Object packagePay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
				@RequestHeader (value="SECRET", required=false)String member_id,
				@RequestHeader (value="LANG", required=false)String lang,
				String package_id,String address_id,String pay_pwd,String standard_id,HttpServletRequest request,String address_obj_en) throws Exception{
			
			int packageCount = memberCartServise.getPackageCountByMemberId(member_id);
			if(packageCount>0){
				return PackageUtil.packageParams(10922,"套餐已购买","",""); 
			}
			
			String os =  request.getHeader("OS");
			String order_from   = "1";
			if (os != null) {
				os = os.toLowerCase();
			}
			if("wechat".equals(os)){
				order_from = "2";
			}
			else if("web".equals(os)){
				order_from = "3";
			}
			else if("ios".equals(os)||"android".equals(os)){
				order_from = "1";
			}
			
			if(address_id == null || "".equals(address_id)||package_id == null || "".equals(package_id)||standard_id == null || "".equals(standard_id)){
				return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
			}
			
			
			AddressVO addressVO = new AddressVO();
			String country = "";
			if(lang==null){
				country = "1";
				addressVO = memberCartServise.getMemberAddressById(address_id);
				if(addressVO==null){
					addressVO = new AddressVO();
					return PackageUtil.packageParams(10901,"收货地址错误",addressVO,""); 
				}
				
			}
			else if(lang.equals("en")){
				country = "0";
				if(address_obj_en==null){
					return PackageUtil.packageParams(10901,"收货地址错误","",""); 
				}
				addressVO.setAddress_obj_en(address_obj_en);
			}
			
			MemberVO member = new MemberVO();
			member.setId(member_id);
			member = memberService.getAllInfoById(member_id);
			member.setPay_pwd(pay_pwd);
			int total = memberService.chekPayPwd(member);
			//member = memberCartServise.getMemberById(member_id);
			if(total == 0){
				return PackageUtil.packageParams(12005,"支付密码错误","","");
			}
			PackageVO pack = new PackageVO();
			//判断商品正确性   
			int check = payService.checkPackage(package_id,standard_id);
			if(check==0){
				return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
			}	
			//查询套餐
			pack = memberService.getGoodPackage(package_id,standard_id);
			
			if(pack==null){
				return PackageUtil.packageParams(10202,"套餐不存在","","");
			}

			if(Integer.parseInt(pack.getNum())<1){
				//库存不够
				return PackageUtil.packageParams(10909,"库存不足","","");
			}
			
			Map<String, Object> map = payService.insertPackage(pack,member,addressVO,"1",null,order_from,country);
			return map;
		}
		
		
		
		@RequestMapping(value="/orderPayPal",method=RequestMethod.POST)
		public String orderPayPal(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="OS", required=false) String os,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String order_pay_no,String return_url, String cancel_url) throws NumberFormatException, Exception{
			
			String[] order_id_List = order_pay_no.split(",");
			if (order_id_List == null || "".equals(order_id_List)  ) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
				out.flush();
				out.close();
				return null;
			}
			
			String money = orderService.getTotalPriceByPayNo(order_id_List,member_id);
			if (!StringUtil.isPrice(money)) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
				out.flush();
				out.close();
				return null;
			}
			int payStateCount = orderService.checkOrderPayState(order_id_List);
			if(payStateCount!=order_id_List.length){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			//付款时间倒计时暂停
			int payCount = orderService.stopOrderPayTimerByPayNo(order_id_List);
			if(payCount==0){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			
			memberVO = memberService.getAllInfoById(member_id);
			String no = payService.genPayOrder(1,money,"paypal订单支付",5, member_id);
			//保存参数
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", order_pay_no);
			if("wechat".equals(os)){
				map.put("trade_type", "JSAPI");
			}else if("android".equals(os)||"ios".equals(os)){
				map.put("trade_type", "APP");
			}
			
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			//订单支付
			
			request.setAttribute("return_url", return_url);
			request.setAttribute("cancel_url", cancel_url);
			request.setAttribute("payType", 3);
			request.setAttribute("order_no", no);
			request.setAttribute("price", money);
			request.setAttribute("body", "order pay"+no);
			return "forward:paypalPrePay";
			
		}
		
		
		
		@RequestMapping(value="/OrderPayPalNotify",method=RequestMethod.POST)
		public void OrderPayPalNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{

			payVO =  payService.getPayOrderByNo(request.getParameter("order_id"));
			System.out.println(request.getParameter("order_id"));
			// 判断签名是否正确  
			boolean flag = payService.checkPayPalParam(request);
			if(payVO!=null && flag && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String order_id = (String) obj.get("order_pay_no");
				String[] order_id_list = order_id.split(",");
				List<String> order_id_array =  orderService.getRealPayOrderId(order_id_list);
				//业务
				if(order_id_array!=null&&order_id_array.size()>0){
					//修改包裹状态
					uorderPayService.updOrderAndCaseAfterUnnormalPay("5",payVO.getId(),order_id_array);
					//order_pay  state 2  
					payService.updatePayOrderState1("2",payVO.getId());
					//delete order_timer 
					payService.delOrderTimer(order_id_list);
					
					for (int i = 0; i < order_id_array.size(); i++) {
						LogOrder log = new LogOrder();
						log.setOrder_id(order_id_array.get(i));
						log.setMember_id(payVO.getMember_id());
						log.setRemark("pay success");
						orderService.InsertLogOrder(log);
					}
					MemberVO member= memberService.getAllInfoById(payVO.getMember_id());
					//分润
					benifitAfterOrderPay(order_id_list,member);
					
					order_id_list = new String[order_id_array.size()];
		 			for (int i = 0; i < order_id_array.size(); i++) {
		 				order_id_list[i]= order_id_array.get(i);
		 			}
		 			//订单支付推送
		 			List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_list);
		 			String country =orderList.get(0).getCountry();
		 			pushInterService.pushOrderPay(orderList,country);
				}
			}
		}
		
		
		@RequestMapping(value="/orderPayssionPay",method=RequestMethod.POST)
		public String OrderPayssionPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="OS", required=false) String os,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String order_pay_no,String pay_key) throws NumberFormatException, Exception{
			
			String[] order_id_List = order_pay_no.split(",");
			if (order_id_List == null || "".equals(order_id_List)  ) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001, "缺少必选参数", "", "")));
				out.flush();
				out.close();
				return null;
			}
			
			String money = orderService.getTotalPriceByPayNo(order_id_List,member_id);
			if (!StringUtil.isPrice(money)) {
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10000, "参数不正确", "", "")));
				out.flush();
				out.close();
				return null;
			}
			int payStateCount = orderService.checkOrderPayState(order_id_List);
			if(payStateCount!=order_id_List.length){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			//付款时间倒计时暂停
			int payCount = orderService.stopOrderPayTimerByPayNo(order_id_List);
			if(payCount==0){
				response.setContentType("text/json;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print(JSON.toJSONString(PackageUtil.packageParams(10906,"订单状态异常","","")));
				out.flush();
				out.close();
				return null;
			}
			
			memberVO = memberService.getAllInfoById(member_id);
			String no = payService.genPayOrder(1,money,"payssion订单支付",6, member_id);
			//保存参数
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", order_pay_no);
			map.put("payKey", pay_key);
			if("wechat".equals(os)){
				map.put("trade_type", "JSAPI");
			}else if("android".equals(os)||"ios".equals(os)){
				map.put("trade_type", "APP");
			}
			
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			//订单支付
			request.setAttribute("payType", 3);
			request.setAttribute("order_no", no);
			request.setAttribute("price", money);
			request.setAttribute("body", "order pay");
			request.setAttribute("payKey", pay_key);
			return "forward:payssionPrePay";
			
		}
		
		@RequestMapping(value="/OrderPayssionPayNotify",method=RequestMethod.POST)
		public void OrderPayssionPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
			
			//解析参数
			Map<String,String> params = payService.resolveAPayssionParam(request);
			payVO =  payService.getPayOrderByNo(params.get("order_id"));
			// 判断签名是否正确  
			boolean flag = payService.checkPayssionParam(payVO, params);
			if(flag && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String order_id = (String) obj.get("order_pay_no");
				String[] order_id_list = order_id.split(",");
				List<String> order_id_array =  orderService.getRealPayOrderId(order_id_list);
				//业务
				if(order_id_array!=null&&order_id_array.size()>0){
					//修改包裹状态
					uorderPayService.updOrderAndCaseAfterUnnormalPay("6",payVO.getId(),order_id_array);
					//order_pay  state 2  
					payService.updatePayOrderState1("2",payVO.getId());
					//delete order_timer 
					payService.delOrderTimer(order_id_list);
					
					for (int i = 0; i < order_id_array.size(); i++) {
						LogOrder log = new LogOrder();
						log.setOrder_id(order_id_array.get(i));
						log.setMember_id(payVO.getMember_id());
						log.setRemark("pay success");
						orderService.InsertLogOrder(log);
					}
					MemberVO member= memberService.getAllInfoById(payVO.getMember_id());
					//分润
					benifitAfterOrderPay(order_id_list,member);
					
					order_id_list = new String[order_id_array.size()];
		 			for (int i = 0; i < order_id_array.size(); i++) {
		 				order_id_list[i]= order_id_array.get(i);
		 			}
		 			//订单支付推送
		 			List<OrderVO> orderList = orderService.getSimpleOrderByIdList(order_id_list);
		 			String country = orderList.get(0).getCountry();
		 			if("1".equals(country)){
		 				pushService.pushOrderPay(orderList);
		 			}else{
		 				pushInterService.pushOrderPay(orderList,country);
		 			}
				}
			}
		}
		
		@RequestMapping(value="/packagePayPal",method=RequestMethod.POST)
		public String packagePayPal(@RequestHeader (value="AUTHORIZATION", required=false) String token,
				@RequestHeader (value="SECRET", required=false)  String member_id,
				@RequestHeader (value="LANG", required=false) String lang,
				String pay_key,
				HttpServletRequest request, HttpServletResponse response
				,String package_id,String address_id,String standard_id,
				String cancel_url,String return_url,String address_obj_en) throws IOException{
			
			//验证参数
			if( package_id==null||"".equals(package_id)||standard_id==null||"".equals(standard_id)|| address_id==null||"".equals(address_id)){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
				out.flush();
				out.close();
				return null;
			}
					
			int packageCount = memberCartServise.getPackageCountByMemberId(member_id);
			if(packageCount>0){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10922,"套餐已购买","","")));
				out.flush();
				out.close();
				return null;
			}
			
			
			AddressVO addressVO = new AddressVO();
			if(address_obj_en==null){
					response.setContentType("text/json;charset=utf-8");   
					PrintWriter out = response.getWriter(); 
					out.print(JSON.toJSONString(PackageUtil.packageParams(10901,"收货地址错误",addressVO,"")));
					out.flush();
					out.close();
					return null;
			}
			addressVO.setAddress_obj_en(address_obj_en);
			
			PackageVO pack = new PackageVO();
			
			int check = payService.checkPackage(package_id,standard_id);
			if(check==0){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10202,"套餐不存在","","")));
				out.flush();
				out.close();
				return null;
			}	
			//查询套餐
			pack = memberService.getGoodPackage(package_id,standard_id);
			
			if(Integer.parseInt(pack.getNum())<1){
				//库存不够
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10909,"库存不足","","")));
				out.flush();
				out.close();
				return null;
			}
			
			String no = payService.genPayOrder(1,pack.getPrice(),"微信套餐支付",1, member_id);
			
			String os =  request.getHeader("OS");
			String order_from   = "1";
			if (os != null) {
				os = os.toLowerCase();
			}
			if("wechat".equals(os)){
				order_from = "2";
			}
			else if("web".equals(os)){
				order_from = "3";
			}
			else if("ios".equals(os)||"android".equals(os)){
				order_from = "1";
			}
			
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", no);
			map.put("ticket", pack.getTicket());
			map.put("price", pack.getPrice());
			map.put("freight", "0");
			map.put("join_cash", pack.getJoin_cash());
			map.put("address_id", address_id);
			map.put("address_obj_en", address_obj_en);
			map.put("package_id", package_id);
			map.put("order_from",order_from);
			map.put("lang", lang);
			map.put("payKey", pay_key);
			
			if(standard_id==null||"".equals(standard_id)){
				map.put("standard_id", pack.getGood_standard_id());
			}else{
				map.put("standard_id", standard_id);
			}
			
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			
			//套餐购买
			request.setAttribute("cancel_url", cancel_url);
			request.setAttribute("return_url", return_url);
			request.setAttribute("payType", 4);
			request.setAttribute("order_no", no);
			request.setAttribute("price", pack.getPrice());
			request.setAttribute("body", "package pay");
			return "forward:paypalPrePay";
			
		}
		
		@RequestMapping(value="/packagePayPalNotify",method=RequestMethod.POST)
		public void packagePayPalNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
			System.out.println("-------------------------------come in ticketPaypalNotify--------------------------------------------");
			payVO =  payService.getPayOrderByNo(request.getParameter("order_id"));
			System.out.println(request.getParameter("order_id"));
			// 判断签名是否正确  
			boolean flag = payService.checkPayPalParam(request);
			if(payVO!=null && flag && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String ticket = obj.get("ticket").toString();
				String price = obj.get("price").toString();
				String join_cash = obj.get("join_cash").toString();
				String address_id = obj.get("address_id").toString();
				String address_obj_en = obj.get("address_obj_en").toString();
				String package_id = obj.get("package_id").toString();
				String standard_id = obj.get("standard_id").toString();
				String order_from = obj.get("order_from").toString();
				String conn_pay_id = payVO.getId();
				PackageVO pack = memberService.getGoodPackage(package_id,standard_id);
				
				AddressVO addressVO = addressService.getAddressByIdEn(address_id);
				addressVO.setAddress_obj_en(address_obj_en);
				
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				payVO.setPay_type("4");
				payService.insertPackage1(pack,memberVO,addressVO,"5",conn_pay_id,payVO,order_from,"0");
				
				//******************************支付成功业务逻辑end**************************************//
			}else{
				
			}
		}
	
		@RequestMapping(value="/packagePayssionPay",method=RequestMethod.POST)
		public String packagePayssionPay(@RequestHeader (value="AUTHORIZATION", required=false) String token,
				@RequestHeader (value="SECRET", required=false)  String member_id,
				@RequestHeader (value="LANG", required=false) String lang,
				String pay_key,
				HttpServletRequest request, HttpServletResponse response
				,String package_id,String address_id,String standard_id,
				String cancel_url,String return_url,String address_obj_en) throws IOException{
			
			//验证参数
			if( package_id==null||"".equals(package_id)||standard_id==null||"".equals(standard_id)|| address_id==null||"".equals(address_id)){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10001,"缺少必选参数","","")));
				out.flush();
				out.close();
				return null;
			}
					
			int packageCount = memberCartServise.getPackageCountByMemberId(member_id);
			if(packageCount>0){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10922,"套餐已购买","","")));
				out.flush();
				out.close();
				return null;
			}
			
			AddressVO addressVO = new AddressVO();
			if(address_obj_en==null){
					response.setContentType("text/json;charset=utf-8");   
					PrintWriter out = response.getWriter(); 
					out.print(JSON.toJSONString(PackageUtil.packageParams(10901,"收货地址错误",addressVO,"")));
					out.flush();
					out.close();
					return null;
			}
			addressVO.setAddress_obj_en(address_obj_en);
			
			PackageVO pack = new PackageVO();
			
			int check = payService.checkPackage(package_id,standard_id);
			if(check==0){
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10202,"套餐不存在","","")));
				out.flush();
				out.close();
				return null;
			}	
			//查询套餐
			pack = memberService.getGoodPackage(package_id,standard_id);
			
			if(Integer.parseInt(pack.getNum())<1){
				//库存不够
				response.setContentType("text/json;charset=utf-8");   
				PrintWriter out = response.getWriter(); 
				out.print(JSON.toJSONString(PackageUtil.packageParams(10909,"库存不足","","")));
				out.flush();
				out.close();
				return null;
			}
			
			String no = payService.genPayOrder(1,pack.getPrice(),"payssion套餐支付",1, member_id);
			
			String os =  request.getHeader("OS");
			String order_from   = "1";
			if (os != null) {
				os = os.toLowerCase();
			}
			if("wechat".equals(os)){
				order_from = "2";
			}
			else if("web".equals(os)){
				order_from = "3";
			}
			else if("ios".equals(os)||"android".equals(os)){
				order_from = "1";
			}
			
			Map<String,String> map =new HashMap<String, String>();
			map.put("order_pay_no", no);
			map.put("ticket", pack.getTicket());
			map.put("price", pack.getPrice());
			map.put("freight", "0");
			map.put("join_cash", pack.getJoin_cash());
			map.put("address_id", address_id);
			map.put("address_obj_en", address_obj_en);
			map.put("package_id", package_id);
			map.put("order_from",order_from);
			map.put("lang", lang);
			map.put("payKey", pay_key);
			
			if(standard_id==null||"".equals(standard_id)){
				map.put("standard_id", pack.getGood_standard_id());
			}else{
				map.put("standard_id", standard_id);
			}
			
			payService.updatePayOrderParams(no,JSON.toJSONString(map));
			
			//套餐购买\
			request.setAttribute("return_url", return_url);
			request.setAttribute("cancel_url", cancel_url);
			request.setAttribute("payKey", pay_key);
			request.setAttribute("payType", 4);
			request.setAttribute("order_no", no);
			request.setAttribute("price", pack.getPrice());
			request.setAttribute("body", "package pay");
			return "forward:payssionPrePay";
			
		}
		
		@RequestMapping(value="/packagePayssionPayNotify",method=RequestMethod.POST)
		public void packagePayssionPayNotify(@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)  String member_id,HttpServletRequest request, HttpServletResponse response
				,MemberVO memberVO, String free_cash,OrderPayVO payVO) throws Exception{
			System.out.println("-------------------------------come in ticketPayssionPayNotify--------------------------------------------");
			//解析参数
			Map<String,String> params = payService.resolveAPayssionParam(request);
			payVO =  payService.getPayOrderByNo(params.get("order_id"));
			// 判断签名是否正确  
			boolean flag = payService.checkPayssionParam(payVO, params);
			if(flag && "N".equals(payVO.getPay_yn())){
				int re = payService.updateOrderPayFinish(payVO);
				if(re==0){
					return;
				}
				
				JSONObject obj = JSON.parseObject(payVO.getParams());
				String ticket = obj.get("ticket").toString();
				String price = obj.get("price").toString();
				String join_cash = obj.get("join_cash").toString();
				String address_id = obj.get("address_id").toString();
				String address_obj_en = obj.get("address_obj_en").toString();
				String package_id = obj.get("package_id").toString();
				String standard_id = obj.get("standard_id").toString();
				String order_from = obj.get("order_from").toString();
				String conn_pay_id = payVO.getId();
				PackageVO pack = memberService.getGoodPackage(package_id,standard_id);
				AddressVO addressVO = addressService.getAddressByIdEn(address_id);
				addressVO.setAddress_obj_en(address_obj_en);
				memberVO = memberService.getAllInfoById(payVO.getMember_id());
				payVO.setPay_type("4");
				payService.insertPackage1(pack,memberVO,addressVO,"6",conn_pay_id,payVO,order_from,"0");
				
			}
		}
}
